package com.anlogic.sdk.ui.tests.utils;


import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.widgetOfType;
import static org.eclipse.swtbot.swt.finder.waits.Conditions.waitForWidget;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;

import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.eclipse.finder.waits.Conditions;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.forms.finder.SWTFormsBot;
import org.eclipse.swtbot.forms.finder.widgets.SWTBotHyperlink;
import org.eclipse.swtbot.swt.finder.waits.DefaultCondition;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCombo;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotList;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotRadio;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.TimeoutException;


public class DriverAppUtitls {
	public static void driverAppTest(SWTWorkbenchBot bot,SWTFormsBot fbot,String core,String width,String appName,int no) throws InterruptedException {
		bot.waitUntil(Conditions.shellIsActive("data - FutureDynasty"),90000);
		

		 bot.waitUntil(new DefaultCondition() {
	            @Override
	            public boolean test() throws Exception {
	                // 检查菜单是否可用
	                return bot.menu("File").menu("New").menu("Platform Project").isEnabled();
	            }

	            @Override
	            public String getFailureMessage() {
	                return "Menu 'Platform Project' is not available or not enabled.";
	            }
	        },90*1000);

	        // 如果菜单项已经可用，进行点击
	        bot.menu("File").menu("New").menu("Platform Project").click();
		final SWTBotShell[] emptyTitleShell = new SWTBotShell[1];

		bot.waitUntil(new DefaultCondition() {
			public boolean test() {
				for (SWTBotShell shell : bot.shells()) {
					if ("".equals(shell.getText()) && shell.isOpen()) {
						emptyTitleShell[0] = shell;
						return true;
					}
				}
				return false;
			}

			public String getFailureMessage() {
				return "no find shell";
			}
		}, 20000);

		
		SWTBotShell activeShell = emptyTitleShell[0].activate();
		activeShell.activate();
		activeShell.setFocus();
		bot.shell("").activate().setFocus();
		Thread.sleep(1000);
		bot.textWithLabel("Project Name:").setText("platform");
		

		// 等待第一个 Combo 出现
		//bot.waitUntil(Conditions.widgetIsEnabled(bot.comboBox(0)), 10000);
		bot.comboBox(0).setSelection("AD101V20");

		
		bot.comboBox(1).setSelection("standalone");

		// 等待第三个 Combo 出现
		//bot.waitUntil(Conditions.widgetIsEnabled(bot.comboBox(2)), 10000);
		bot.comboBox(2).setSelection(core);
		bot.waitUntil(Conditions.widgetIsEnabled(bot.button("Finish")), 20000);
		 bot.button("Finish").click();
		 	bot.waitUntil(Conditions.shellCloses(emptyTitleShell[0]), 120000);

		bot.viewByTitle("Project Explorer").show();
		SWTBotShell activeShell2 = bot.shell("data - FutureDynasty");
		activeShell2.activate();
		activeShell2.setFocus();
		bot.waitUntil(Conditions.shellIsActive("data - FutureDynasty"),20000);
		bot.viewByTitle("Project Explorer").setFocus();
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree(0)), 1000 * 60*2);
		
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform")), 1000 * 60*2);
		
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").select();

		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").doubleClick();

		//bot.waitUntil(Conditions.widgetIsEnabled(bot.tree().getTreeItem("platform").getNode("system.mss")), 1000 * 60);
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").getNode("system.mss").select();

		//bot.waitUntil(Conditions.widgetIsEnabled(bot.tree().getTreeItem("platform").getNode("system.mss")), 1000 * 60);
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").getNode("system.mss").doubleClick();

		bot.editorByTitle("system.mss").show();
		bot.editorByTitle("system.mss").setFocus();
		// 等待第一个链接可用，然后点击
		// 1. 获取点击前已有的所有 Shell 窗口
		List<SWTBotShell> beforeShells = Arrays.asList(fbot.shells());

		// 2. 找到并点击超链接
		SWTBotHyperlink link = fbot.hyperlink("Import Examples", no);
		fbot.waitUntil(Conditions.widgetIsEnabled(link), 30_000);

		// 重试点击逻辑
		final int MAX_RETRIES = 10;
		for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
		    System.out.println("第 " + attempt + " 次点击链接…");
		    link.click();

		    try {
		        // 3. 等待新增 Shell 出现
		        fbot.waitUntil(new DefaultCondition() {
		            @Override
		            public boolean test() throws Exception {
		                return fbot.shells().length > beforeShells.size();
		            }
		            @Override
		            public String getFailureMessage() {
		                return "";
		            }
		        }, 10*1000);

		        System.out.println("弹窗已出现！");
		        break;  // 成功弹出，退出重试循环

		    } catch (TimeoutException e) {
		        System.out.println("第 " + attempt + " 次点击失败，准备重试…");
		        // 每次点击后等待 link 恢复可用
		        fbot.waitUntil(Conditions.widgetIsEnabled(link), 10_000);
		        if (attempt == MAX_RETRIES) {
		            throw new RuntimeException("多次点击后仍未弹出 Import Examples 对话框", e);
		        }
		    }
		}
		SWTBotShell[] emptyTitleShell1=new SWTBotShell[1];
		// 4. 识别新弹出的 Shell
		emptyTitleShell1[0] = Arrays.stream(fbot.shells())
		    .filter(shell -> !beforeShells.contains(shell) && shell.isOpen())
		    .findFirst()
		    .orElseThrow(() -> new RuntimeException("未能识别新弹出的 Import Examples 对话框"));
		emptyTitleShell1[0].activate();
		emptyTitleShell1[0].setFocus();

	
		/*
		 * emptyTitleShell1[0] = bot.shell("").activate(); SWTBotShell activeShell1 =
		 * emptyTitleShell1[0].activate(); activeShell1.activate();
		 * emptyTitleShell1[0].setFocus();
		 */
		
		// 等待 List 出现并选择
		emptyTitleShell1[0] = bot.shell("").activate();
		emptyTitleShell1[0].setFocus();
		bot.comboBox(0).setSelection(width);
		
		bot.list(0).select(appName);
		
		
		/*
		 * SWTBotRadio radio = bot.radio("C");
		 * bot.waitUntil(Conditions.widgetIsEnabled(radio)); // 等待可点击 radio.click();
		 */
		bot.textWithLabel("Project Name:").setText("app");

		bot.waitUntil(Conditions.widgetIsEnabled(bot.button("Create")), 10000);
		 bot.button("Create").click();
		 bot.waitUntil(Conditions.shellCloses(emptyTitleShell1[0]), 120000);
		bot.viewByTitle("Project Explorer").show();

		
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree()),20000);
		bot.viewByTitle("Project Explorer").bot().tree().select("app").contextMenu("Build Project").click();
		SWTBotView consoleView = bot.viewByPartName("Console");
		consoleView.setFocus();
		if (consoleView.isActive()) {
			System.out.println(111);
			Pattern p = Pattern.compile(".*Build Finished. 0 errors.*", Pattern.DOTALL);

			bot.waitUntil(BspAppTestUtils.consoleTextMatches(consoleView, p), 90 * 1000);
		}

	}
	
	public static void dr1v_driverAppTest(SWTWorkbenchBot bot,SWTFormsBot fbot,String core,String appName,int no) throws InterruptedException {
		bot.waitUntil(Conditions.shellIsActive("data - FutureDynasty"),90000);
		

		 bot.waitUntil(new DefaultCondition() {
	            @Override
	            public boolean test() throws Exception {
	                // 检查菜单是否可用
	                return bot.menu("File").menu("New").menu("Platform Project").isEnabled();
	            }

	            @Override
	            public String getFailureMessage() {
	                return "Menu 'Platform Project' is not available or not enabled.";
	            }
	        },90*1000);

	        // 如果菜单项已经可用，进行点击
	        bot.menu("File").menu("New").menu("Platform Project").click();
		final SWTBotShell[] emptyTitleShell = new SWTBotShell[1];

		bot.waitUntil(new DefaultCondition() {
			public boolean test() {
				for (SWTBotShell shell : bot.shells()) {
					if ("".equals(shell.getText()) && shell.isOpen()) {
						emptyTitleShell[0] = shell;
						return true;
					}
				}
				return false;
			}

			public String getFailureMessage() {
				return "no find shell";
			}
		}, 20000);

		
		SWTBotShell activeShell = emptyTitleShell[0].activate();
		activeShell.activate();
		activeShell.setFocus();
		bot.shell("").activate().setFocus();
		Thread.sleep(1000);
		bot.textWithLabel("Project Name:").setText("platform");
		

		// 等待第一个 Combo 出现
		//bot.waitUntil(Conditions.widgetIsEnabled(bot.comboBox(0)), 10000);
		bot.comboBox(0).setSelection("AD102V20");

		
		bot.comboBox(1).setSelection("standalone");

		// 等待第三个 Combo 出现
		//bot.waitUntil(Conditions.widgetIsEnabled(bot.comboBox(2)), 10000);
		bot.comboBox(2).setSelection(core);
		bot.waitUntil(Conditions.widgetIsEnabled(bot.button("Finish")), 20000);
		 bot.button("Finish").click();
		 	bot.waitUntil(Conditions.shellCloses(emptyTitleShell[0]), 120000);

		bot.viewByTitle("Project Explorer").show();
		SWTBotShell activeShell2 = bot.shell("data - FutureDynasty");
		activeShell2.activate();
		activeShell2.setFocus();
		bot.waitUntil(Conditions.shellIsActive("data - FutureDynasty"),20000);
		bot.viewByTitle("Project Explorer").setFocus();
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree(0)), 1000 * 60*2);
		
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform")), 1000 * 60*2);
		
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").select();

		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").doubleClick();

		//bot.waitUntil(Conditions.widgetIsEnabled(bot.tree().getTreeItem("platform").getNode("system.mss")), 1000 * 60);
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").getNode("system.mss").select();

		//bot.waitUntil(Conditions.widgetIsEnabled(bot.tree().getTreeItem("platform").getNode("system.mss")), 1000 * 60);
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").getNode("system.mss").doubleClick();

		bot.editorByTitle("system.mss").show();
		bot.editorByTitle("system.mss").setFocus();
		// 等待第一个链接可用，然后点击
		// 1. 获取点击前已有的所有 Shell 窗口
		List<SWTBotShell> beforeShells = Arrays.asList(fbot.shells());

		// 2. 找到并点击超链接
		SWTBotHyperlink link = fbot.hyperlink("Import Examples", no);
		fbot.waitUntil(Conditions.widgetIsEnabled(link), 30_000);

		// 重试点击逻辑
		final int MAX_RETRIES = 10;
		for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
		    System.out.println("第 " + attempt + " 次点击链接…");
		    link.click();

		    try {
		        // 3. 等待新增 Shell 出现
		        fbot.waitUntil(new DefaultCondition() {
		            @Override
		            public boolean test() throws Exception {
		                return fbot.shells().length > beforeShells.size();
		            }
		            @Override
		            public String getFailureMessage() {
		                return "";
		            }
		        }, 10*1000);

		        System.out.println("弹窗已出现！");
		        break;  // 成功弹出，退出重试循环

		    } catch (TimeoutException e) {
		        System.out.println("第 " + attempt + " 次点击失败，准备重试…");
		        // 每次点击后等待 link 恢复可用
		        fbot.waitUntil(Conditions.widgetIsEnabled(link), 10_000);
		        if (attempt == MAX_RETRIES) {
		            throw new RuntimeException("多次点击后仍未弹出 Import Examples 对话框", e);
		        }
		    }
		}
		SWTBotShell[] emptyTitleShell1=new SWTBotShell[1];
		// 4. 识别新弹出的 Shell
		emptyTitleShell1[0] = Arrays.stream(fbot.shells())
		    .filter(shell -> !beforeShells.contains(shell) && shell.isOpen())
		    .findFirst()
		    .orElseThrow(() -> new RuntimeException("未能识别新弹出的 Import Examples 对话框"));
		emptyTitleShell1[0].activate();
		emptyTitleShell1[0].setFocus();

	
		/*
		 * emptyTitleShell1[0] = bot.shell("").activate(); SWTBotShell activeShell1 =
		 * emptyTitleShell1[0].activate(); activeShell1.activate();
		 * emptyTitleShell1[0].setFocus();
		 */
		
		// 等待 List 出现并选择
		emptyTitleShell1[0] = bot.shell("").activate();
		emptyTitleShell1[0].setFocus();
		//bot.comboBox(0).setSelection(width);
		
		bot.list(0).select(appName);
		
		
		//SWTBotRadio radio = bot.radio("C");
		//bot.waitUntil(Conditions.widgetIsEnabled(radio));  // 等待可点击
		//radio.click();
		bot.textWithLabel("Project Name:").setText("app");

		bot.waitUntil(Conditions.widgetIsEnabled(bot.button("Create")), 10000);
		 bot.button("Create").click();
		 bot.waitUntil(Conditions.shellCloses(emptyTitleShell1[0]), 120000);
		bot.viewByTitle("Project Explorer").show();

		
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree()),20000);
		bot.viewByTitle("Project Explorer").bot().tree().select("app").contextMenu("Build Project").click();
		SWTBotView consoleView = bot.viewByPartName("Console");
		consoleView.setFocus();
		if (consoleView.isActive()) {
			System.out.println(111);
			Pattern p = Pattern.compile(".*Build Finished. 0 errors.*", Pattern.DOTALL);

			bot.waitUntil(BspAppTestUtils.consoleTextMatches(consoleView, p), 90 * 1000);
		}
	}
	
	public static void ph1p35_driverAppTest(SWTWorkbenchBot bot,SWTFormsBot fbot,String core,String appName,int no) throws InterruptedException {
		bot.waitUntil(Conditions.shellIsActive("data - FutureDynasty"),90000);
		

		 bot.waitUntil(new DefaultCondition() {
	            @Override
	            public boolean test() throws Exception {
	                // 检查菜单是否可用
	                return bot.menu("File").menu("New").menu("Platform Project").isEnabled();
	            }

	            @Override
	            public String getFailureMessage() {
	                return "Menu 'Platform Project' is not available or not enabled.";
	            }
	        },90*1000);

	        // 如果菜单项已经可用，进行点击
	        bot.menu("File").menu("New").menu("Platform Project").click();
		final SWTBotShell[] emptyTitleShell = new SWTBotShell[1];

		bot.waitUntil(new DefaultCondition() {
			public boolean test() {
				for (SWTBotShell shell : bot.shells()) {
					if ("".equals(shell.getText()) && shell.isOpen()) {
						emptyTitleShell[0] = shell;
						return true;
					}
				}
				return false;
			}

			public String getFailureMessage() {
				return "no find shell";
			}
		}, 20000);

		
		SWTBotShell activeShell = emptyTitleShell[0].activate();
		activeShell.activate();
		activeShell.setFocus();
		bot.shell("").activate().setFocus();
		Thread.sleep(1000);
		bot.textWithLabel("Project Name:").setText("platform");
		

		// 等待第一个 Combo 出现
		//bot.waitUntil(Conditions.widgetIsEnabled(bot.comboBox(0)), 10000);
		bot.comboBox(0).setSelection("PH1P35");

		
		bot.comboBox(1).setSelection("standalone");

		// 等待第三个 Combo 出现
		//bot.waitUntil(Conditions.widgetIsEnabled(bot.comboBox(2)), 10000);
		bot.comboBox(2).setSelection(core);
		bot.waitUntil(Conditions.widgetIsEnabled(bot.button("Finish")), 20000);
		 bot.button("Finish").click();
		 	bot.waitUntil(Conditions.shellCloses(emptyTitleShell[0]), 120000);

		bot.viewByTitle("Project Explorer").show();
		SWTBotShell activeShell2 = bot.shell("data - FutureDynasty");
		activeShell2.activate();
		activeShell2.setFocus();
		bot.waitUntil(Conditions.shellIsActive("data - FutureDynasty"),20000);
		bot.viewByTitle("Project Explorer").setFocus();
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree(0)), 1000 * 60*2);
		
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform")), 1000 * 60*2);
		
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").select();

		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").doubleClick();

		//bot.waitUntil(Conditions.widgetIsEnabled(bot.tree().getTreeItem("platform").getNode("system.mss")), 1000 * 60);
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").getNode("system.mss").select();

		//bot.waitUntil(Conditions.widgetIsEnabled(bot.tree().getTreeItem("platform").getNode("system.mss")), 1000 * 60);
		bot.viewByTitle("Project Explorer").bot().tree(0).getTreeItem("platform").getNode("system.mss").doubleClick();

		bot.editorByTitle("system.mss").show();
		bot.editorByTitle("system.mss").setFocus();
		// 等待第一个链接可用，然后点击
		// 1. 获取点击前已有的所有 Shell 窗口
		List<SWTBotShell> beforeShells = Arrays.asList(fbot.shells());

		// 2. 找到并点击超链接
		SWTBotHyperlink link = fbot.hyperlink("Import Examples", no);
		fbot.waitUntil(Conditions.widgetIsEnabled(link), 30_000);

		// 重试点击逻辑
		final int MAX_RETRIES = 10;
		for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
		    System.out.println("第 " + attempt + " 次点击链接…");
		    link.click();

		    try {
		        // 3. 等待新增 Shell 出现
		        fbot.waitUntil(new DefaultCondition() {
		            @Override
		            public boolean test() throws Exception {
		                return fbot.shells().length > beforeShells.size();
		            }
		            @Override
		            public String getFailureMessage() {
		                return "";
		            }
		        }, 10*1000);

		        System.out.println("弹窗已出现！");
		        break;  // 成功弹出，退出重试循环

		    } catch (TimeoutException e) {
		        System.out.println("第 " + attempt + " 次点击失败，准备重试…");
		        // 每次点击后等待 link 恢复可用
		        fbot.waitUntil(Conditions.widgetIsEnabled(link), 10_000);
		        if (attempt == MAX_RETRIES) {
		            throw new RuntimeException("多次点击后仍未弹出 Import Examples 对话框", e);
		        }
		    }
		}
		SWTBotShell[] emptyTitleShell1=new SWTBotShell[1];
		// 4. 识别新弹出的 Shell
		emptyTitleShell1[0] = Arrays.stream(fbot.shells())
		    .filter(shell -> !beforeShells.contains(shell) && shell.isOpen())
		    .findFirst()
		    .orElseThrow(() -> new RuntimeException("未能识别新弹出的 Import Examples 对话框"));
		emptyTitleShell1[0].activate();
		emptyTitleShell1[0].setFocus();

	
		/*
		 * emptyTitleShell1[0] = bot.shell("").activate(); SWTBotShell activeShell1 =
		 * emptyTitleShell1[0].activate(); activeShell1.activate();
		 * emptyTitleShell1[0].setFocus();
		 */
		
		// 等待 List 出现并选择
		emptyTitleShell1[0] = bot.shell("").activate();
		emptyTitleShell1[0].setFocus();
		//bot.comboBox(0).setSelection(width);
		
		bot.list(0).select(appName);
		
		
		/*
		 * SWTBotRadio radio = bot.radio("C");
		 * bot.waitUntil(Conditions.widgetIsEnabled(radio)); // 等待可点击 radio.click();
		 */
		bot.textWithLabel("Project Name:").setText("app");

		bot.waitUntil(Conditions.widgetIsEnabled(bot.button("Create")), 10000);
		 bot.button("Create").click();
		 bot.waitUntil(Conditions.shellCloses(emptyTitleShell1[0]), 120000);
		bot.viewByTitle("Project Explorer").show();

		
		bot.waitUntil(Conditions.widgetIsEnabled(bot.viewByTitle("Project Explorer").bot().tree()),20000);
		bot.viewByTitle("Project Explorer").bot().tree().select("app").contextMenu("Build Project").click();
		SWTBotView consoleView = bot.viewByPartName("Console");
		consoleView.setFocus();
		if (consoleView.isActive()) {
			System.out.println(111);
			Pattern p = Pattern.compile(".*Build Finished. 0 errors.*", Pattern.DOTALL);

			bot.waitUntil(BspAppTestUtils.consoleTextMatches(consoleView, p), 90 * 1000);
		}
	}

}
